package factory_pattern.simple_factory;

import factory_pattern.simple_factory.connection_impl.NetworkConnection;
import factory_pattern.simple_factory.connection_impl.TcpConnection;
import factory_pattern.simple_factory.connection_impl.UdpConnection;
import factory_pattern.simple_factory.connection_impl.WebSocketConnection;

// 简单工厂：统一创建网络连接
public class ConnectionFactory {
    // 静态方法：根据类型创建连接
    public static NetworkConnection createConnection(String connType, Object... params) {
        connType = connType.toLowerCase();
        switch (connType) {
            case "tcp":
                // 校验TCP参数（需2个参数：host(String)、port(int)）
                if (params.length != 2 || !(params[0] instanceof String) || !(params[1] instanceof Integer)) {
                    throw new IllegalArgumentException("TCP连接需传入 [String host, Integer port]");
                }
                return new TcpConnection((String) params[0], (Integer) params[1]);

            case "udp":
                if (params.length != 2 || !(params[0] instanceof String) || !(params[1] instanceof Integer)) {
                    throw new IllegalArgumentException("UDP连接需传入 [String host, Integer port]");
                }
                return new UdpConnection((String) params[0], (Integer) params[1]);

            case "ws":
                if (params.length != 1 || !(params[0] instanceof String)) {
                    throw new IllegalArgumentException("WebSocket连接需传入 [String url]");
                }
                return new WebSocketConnection((String) params[0]);

            default:
                throw new IllegalArgumentException("不支持的连接类型：" + connType + "（仅支持 tcp/udp/ws）");
        }
    }
}